// services/socketService.ts
import { io, Socket } from "socket.io-client";
import { store } from "../store";

const serverUrl = import.meta.env.VITE_WS_SERVER_URL

// 定义消息类型（根据后端广播的结构）
interface ChatMessage {
    message_id:string,
    channel_id:string,
    direct_chat_id:string,
    content:string,
    sender_id:string,
    created_at:string,
    sender_avatar:string,
    sender_name:string
}

class SocketService {
    private socket: Socket | null = null;
    private token: string | null = null;
    private heartbeatInterval: NodeJS.Timeout | null = null;
    private heartbeatTimeout: NodeJS.Timeout | null = null;
    private readonly heartbeatIntervalTime = 25000; // 25秒发送一次心跳
    private readonly heartbeatTimeoutTime = 5000;  // 5秒内未收到响应则断开

    // 初始化Socket连接
    async connect(): Promise<void> {
        this.token = store.getState().auth.token; // 从本地存储获取token
        
        if (!this.token) {
            console.error("No token available, please log in.");
            return;
        }
        
        this.socket = io(`${serverUrl}?token=${this.token}`, {
            extraHeaders: {
                Authorization: `Bearer ${this.token}`,
            },
            transports: ["websocket"], // 推荐使用websocket传输
            reconnection: true,
            reconnectionAttempts: Infinity,
            reconnectionDelay: 1000,
            reconnectionDelayMax: 5000,
        });

        // 连接事件处理
        this.setupHeartbeat()
        
        this.socket.emit("join_host");

        // 错误处理
        this.socket.on("connect_error", (err) => {
            console.error("Socket connection error:", err);
            // 可以在这里添加重连逻辑
        });

        this.socket.on('message_error', (error: any) => {
            console.log('Error:', error);
            // 恢复被删除的消息或移除发送中的消息
            // 根据实际情况实现...
        });

        this.socket.on('delete_message_success',(message_id:string)=>{
            console.log("Message deleted:", message_id);
            
        })

        this.socket.on('send_message_success',(message: ChatMessage)=>{
            console.log("Message sent:", message);
        })

        // 监听心跳响应
        this.socket.on("pong", () => {
            this.resetHeartbeatTimeout();
        });
    }

        // 设置心跳机制
    private setupHeartbeat(): void {
        // 清理已有定时器
        this.clearHeartbeatTimers();
        
        if (!this.socket) return;

        // 监听连接成功后再启动心跳
        this.socket.on("connectSuccess", () => {
            console.log("Socket connected - starting heartbeat");
            
            // 定期发送心跳
            this.heartbeatInterval = setInterval(() => {
                this.sendHeartbeat();
            }, this.heartbeatIntervalTime);
            
        });

        // 连接断开时清理心跳
        this.socket.on("disconnect", () => {
            console.log("Socket disconnected - stopping heartbeat");
            this.socket?.emit('disconnectUser',{
                user_id: store.getState().auth.user_id,
                userType: store.getState().auth.userType
            })
            this.clearHeartbeatTimers();
        });
    }

    // 发送心跳包
    private sendHeartbeat(): void {
        if (!this.socket || !this.socket.connected) {
            console.warn("Cannot send heartbeat - socket not connected");
            return;
        }
        console.log("Sending ping...");

        this.socket.emit("ping",{
            user_id: store.getState().auth.user_id,
        });

        // 设置超时检测
        this.heartbeatTimeout = setTimeout(() => {
            console.error("Heartbeat timeout - forcing disconnect");
            this.socket?.disconnect();
        }, this.heartbeatTimeoutTime);
    }

    // 重置心跳超时
    private resetHeartbeatTimeout(): void {
        console.log("Received pong");
        if (this.heartbeatTimeout) {
            clearTimeout(this.heartbeatTimeout);
        }
    }

    // 清理所有心跳定时器
    private clearHeartbeatTimers(): void {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
        if (this.heartbeatTimeout) {
            clearTimeout(this.heartbeatTimeout);
            this.heartbeatTimeout = null;
        }
    }

    // 加入频道房间
    joinChannel(channelId: string): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("join_channel", {
            channel_id: channelId,
        });
    }

    // 离开频道房间
    leaveChannel(channelId: string): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("leave_channel", {
            channel_id: channelId,
            user_id: store.getState().auth.user_id,
        });
    }

    // 发送消息
    async sendMessage(channel_id: string, content: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("send_message", {
            channel_id: channel_id,
            content: content,
        });
    }

    // 删除消息
    async deleteMessage(message_id: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("delete_message", {
            message_id: message_id,
        });
    }

    // 更改用户状态
    async changeUserStatus(status: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("change_user_status", {
            status: status,
        });
    }
    

    // 监听新消息
    onNewMessage(callback: (message: ChatMessage) => void): void {
        
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("send_message_broadcast", callback);
    }

    // 监听删除消息
    onDelMessage(callback: ({message_id,channel_id}:{message_id:string,channel_id:string}) => void): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("delete_message_broadcast", callback);
    }

    // 移除监听
    offNewMessage(): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("send_message_broadcast");
    }

    // 监听消息删除
    offDelMessage(): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("delete_message_broadcast");
    }

    // 监听用户状态
    onUserStatus(callback: ({onlineUsers, stealthUser}:{onlineUsers:string[],stealthUser:string[]}) => void): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("broadcast_status", callback);
    }

    // 加入语音频道
    joinVoiceChannel(channelId: string): void { 
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.emit("join_voice_channel", {
            channel_id:channelId
        });
    }

    // 离开语音频道
    leaveVoiceChannel(channelId: string): void { 
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.emit("leave_voice_channel", {
            channel_id: channelId,
            user_id: store.getState().auth.user_id,
        });
    }

    // 监听获取语音房间用户列表
    onSendChatUsers(callback: (users: {users:{avatar_url:string,user_id:string,username:string}[]}) => void){
        if(!this.socket){
            console.error("socket连接失败");
            return;
        }
        this.socket.on("sendChatUsers", (users: any) => {
            callback(users);
        });
    }

    onUsersChange(callback: (data: {user:{avatar_url:string,user_id:string,username:string},type:string}) => void){
        if(!this.socket){
            console.error("socket连接失败");
            return;
        }
        this.socket.on("usersChange", (data: any) => {
            callback(data);
        });
    }

    // 加入语音房间
    async joinVoiceChat(channelId: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("join_voice_chat", {
            channel_id: channelId,
        });
    }

    // 离开语音房间
    leaveVoiceChat(channelId: string): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("leave_voice_chat", {
            channel_id: channelId,
            user_id: store.getState().auth.user_id,
        });
    }

    sendOffer(channelId: string, offer: RTCSessionDescriptionInit, targetUserId: string):void{
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.emit("sendOffer", {
            channel_id: channelId,
            offer: offer,
            target_user_id: targetUserId
        });
    }

    sendAnswer(channelId: string, answer: RTCSessionDescriptionInit, targetUserId: string){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.emit("sendAnswer", {
            channel_id: channelId,
            answer: answer,
            target_user_id: targetUserId
        });
    }

    sendIceCandidate(channelId: string, candidate: RTCIceCandidateInit, targetUserId: string){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.emit("sendIceCandidate", {
            channel_id: channelId,
            candidate: candidate,
            target_user_id: targetUserId
        });
    }

    onOffer(callback: (data: {channel_id: string, offer: RTCSessionDescriptionInit, from_user_id: string}) => void){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("onOffer", callback);
    }

    onAnswer(callback: (data: {channel_id: string, answer: RTCSessionDescriptionInit, from_user_id: string}) => void){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("onAnswer", callback);
    }

    onIceCandidate(callback: (data: {channel_id: string, candidate: RTCIceCandidateInit, from_user_id: string}) => void){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("onIceCandidate", callback);
    }

    onUserJoined(callback: (data:{user_id:string}) => void) {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("userJoined", callback);
    }
    
    onUserLeft(callback: (userId: string) => void) {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.on("userLeft", ({ user_id }) => callback(user_id));
    }

    // 添加取消监听的方法
    offOffer() {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("onOffer");
    }
    
    offAnswer() {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("onAnswer");
    }
    
    offIceCandidate() {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("onIceCandidate");
    }

    offUserJoined() { 
        if (!this.socket) { 
            console.error("socket连接失败");
            return;
        }
        this.socket.off("userJoined");
    }

    offUserLeft(){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("userLeft");
    }

    offSendChatUsers(){
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("sendChatUsers");
    }


    // 移除用户状态监听
    offUserStatus(): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        this.socket.off("broadcast_status");
    }

    // 加入私聊房间
    joinPrivate(chat_id: string): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("join_private", {
            chat_id: chat_id,
        });
    }

    // 离开私聊房间
    leavePrivate(chat_id: string): void {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("leave_private", {
            chat_id: chat_id,
            user_id: store.getState().auth.user_id,
        });
    }

    // 发送私聊消息
    async sendPrivateMessage(chat_id: string, content: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("send_private_message", {
            chat_id: chat_id,
            content: content,
        });
    }
    
    // 删除私聊消息
    async deletePrivateMessage(message_id: string): Promise<void> {
        if (!this.socket) {
            console.error("socket连接失败");
            return;
        }
        
        this.socket.emit("delete_private_message", {
            message_id: message_id,
        });
    }

    // 断开连接
    async disconnect(): Promise<void> {
        if (this.socket) {
            this.socket.disconnect();
            this.socket = null;
        }
    }

    // 获取当前Socket实例（如果需要直接操作）
    getSocket(): Socket | null {
        return this.socket;
    }
}

// 创建单例实例
const socketService = new SocketService();
export default socketService;